import cxy.dao.StudentDao;
import cxy.entity.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;

public class ttt {

    @Test
    public void test() throws IOException {
        // 1. 加载MyBatis配置文件
        InputStream inputStream = Resources.getResourceAsStream("bannianqianjiuxuele-core.xml");

        // 2. 创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        // 3. 获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();

        try {
            // 4. 获取StudentDao接口的代理对象
            StudentDao studentDao = sqlSession.getMapper(StudentDao.class);

            // 5. 执行添加操作
            int result = studentDao.add(new Student("张四", LocalDate.of(2001, 1, 1), new byte[]{1, 2, 3}, 0));
            System.out.println("添加结果: " + result);

            // 6. 提交事务
            sqlSession.commit();
        } catch (Exception e) {
            // 发生异常时回滚事务
            sqlSession.rollback();
            e.printStackTrace();
        } finally {
            // 7. 关闭SqlSession
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }
}
